import { baseUrl } from "./url";
// import { Api } from "./index";
import { refreshTokens } from "./apis.js";

// 保存最近一次请求内容，用于token过期时重复请求
let latestRequest = {};

async function request(params) {
	if(params.url != '/api/apis/refreshTokens'){
		latestRequest = params;
	}
	return new Promise((resolve, reject) => {
	
		uni.request({
		  url: baseUrl+params.url,
		  method: params.method || "POST",
		  data: params.data || {},
		  header: {
			token: uni.getStorageSync("userToken"),
			"content-type":
			  params.contentType || "application/x-www-form-urlencoded",
		  },
		  success: (res) => {
			if (res.data.code == 200 || res.data.code == 1) {
			  resolve(res.data.data);
			} else {
			  reject(res.data);
			}
		  },
		  fail(err) {
			reject(err);
		  },
		});
	});
}

export default request;

// 增加token过期自动重新获取
function refreshToken() {
	let uid = uni.getStorageSync("uid")
	refreshTokens({uid}).then(async(res)=>{
		uni.setStorageSync("userToken",res.token)
		return await request(latestRequest);
	}).catch((err)=>{
		uni.showToast({
			title:"請重新登錄",
			mask:true,
			icon:"none"
		})
		setTimeout(()=>{
			uni.navigateTo({
				url:'/pages/index/index'
			})
		},1200)
	})
}

// request拦截器
uni.addInterceptor("request", {
  invoke(req) {
	// req.url = baseUrl + req.url;
  },
  success(args) {
    const data = args.data;
    if (parseInt(data.code) === 101) {
      // console.log("token过期");
      const reload = refreshToken();
      return reload;
    }else if (parseInt(data.code) === 102) {
	  uni.showToast({
			title:"請重新登錄",
			mask:true,
			icon:"none"
		})
		setTimeout(()=>{
			uni.navigateTo({
				url:'/pages/index/index'
			})
		},1200)
	}else{
		return args;
	}
  },
});
